package com.assistant.wechat.service;


import com.assistant.common.HttpClientUtil;
import com.assistant.common.JsonUtils;
import com.assistant.wechat.mapper.LoginMapper;
import com.assistant.wechat.pojo.WXSessionModel;
import com.assistant.wechat.pojo.WxUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class WxUserService {

    @Autowired
    private LoginMapper loginMapper;

    public void saveUser(WxUser user) {
        loginMapper.insertSelective(user);
    }

    public WXSessionModel login(String code) {
        System.out.println("wxlogin - code: " + code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<>();
        param.put("appid", "wxdb76f2faee9495e9");
        param.put("secret", "ce9b215bc942875e3467ae2ae1708a14");
//          param.put("appid", "wx484404f3cbc25454");
//		  param.put("secret", "8cc8ade16def9b52e26ae0f02e7d0e8c");

//        param.put("appid", "wx907a35057db9b048 ");
//        param.put("secret", "1205b66444e0e2185b32729865c9efdd");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        String wxResult = HttpClientUtil.doGet(url, param);
        WXSessionModel wxSessionModel = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
        return wxSessionModel;
    }

    public List<WxUser> isLogin(String openid) {
        Example example = new Example(WxUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid", openid);
        List<WxUser> wxUsers = loginMapper.selectByExample(example);
        return wxUsers;
    }

    public List<WxUser> getWxuserById(String openid){
        Example example = new Example(WxUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid",openid);
        return loginMapper.selectByExample(example);
    }
}
